var express = require("express");
var http = require("http");
var fs = require('fs');
const path = require('path');
const mineType = require('mime-types');
var app = express();

// 静态资源托管工具

app.use(express.static("./static"));

app.get("/", function(req, res) {
  res.send("Hello");
})

app.post("/file/download", async function(req, res) {
  res.setHeader('Access-Control-Allow-Origin','*');
  function read() {
    return new Promise((resolve, reject) => {
      fs.readFile('./static/images/cat.jpg', function(err, data) {
        resolve(data);
        reject(err);
      })
    })
  }
  let data = await read();
  res.send(data);
})

app.get("/file/pdf", async function(req, res) {
  res.setHeader('Access-Control-Allow-Origin','*');
  function read() {
    return new Promise((resolve, reject) => {
      fs.readFile('./static/pdf/员工手册.pdf', function(err, data) {
        resolve(data);
        reject(err);
      })
    })
  }
  let data = await read();
  res.send(data);
})

app.get("/file/pdfzip", async function(req, res) { // 返回二进制流
  res.setHeader('Access-Control-Allow-Origin','*');
  function read() {
    return new Promise((resolve, reject) => {
      fs.readFile('./static/test.zip', function(err, data) {
        resolve(data);
        reject(err);
      })
    })
  }
  let data = await read();
  res.send(data);
})

app.get("/file/base64", async function(req, res) { // 返回base64
  res.setHeader('Access-Control-Allow-Origin','*');
  let bitmap = fs.readFileSync('./static/test.zip'); // 读取文件
  let base64String = Buffer.from(bitmap, 'binary').toString('base64'); // base64编码
  res.send(base64String);
})



app.get("/toBase64", function(req, res) {
  let filePath = path.resolve('./static/images/cat.jpg');
  let data = fs.readFileSync(filePath);
  data = Buffer.from(data).toString('base64');
  let base64 = 'data:' + mineType.lookup(filePath) + ';base64,' + data;

  // transferToImg(base64); // 将base64转化为图片
  res.send(base64);
})


function transferToImg(data) {

  //过滤data:URL
  let base64Data = data.replace(/^data:image\/\w+;base64,/, "");
  let dataBuffer = Buffer.from(base64Data, 'base64');

  const allowExtname = ['png', 'jpg', 'jpeg', 'webp', 'bmp'];//支持的图片格式

  //获取扩展名
  let extname = '';
  let filterResult=allowExtname.filter(item => {
      return data.includes(item)
  })
  extname='.'+filterResult[0]
  
  //指定目标存放路径
  let targetPath = path.resolve(__dirname, './static/temp')//自定义文件夹
  let filename = new Date().getTime();

  // 写入图片
  fs.writeFileSync(`${targetPath}/${filename}${extname}`, dataBuffer)
}

var httpServer = http.createServer(app);
const PORT = 3000;
const HOSTNAME = '0.0.0.0';
httpServer.listen(PORT, HOSTNAME, function() {
  console.log('Server is running on http://' + HOSTNAME + ':%s', PORT);
})